package cn.itsource.basic.config;

import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.PetConstant;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.domain.UserInfo;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 登录拦截器
 */

@Component //交给spring管理,就可 @Autowired
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;

    /**
     * 进入所有的Controller的方法之前执行
     *
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.从前端请求头里面头拿到token,判断token是否存在 null "null"
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)){
            //1.只能告诉前端2000的code(约定的登录失效的code)
            //除了分页,所有的都返回AjaxResult
            AjaxResult result = AjaxResult.createError(PetConstant.LOGIN_TIME_OUT, "登录失效");
            //1.1设置返回的类型,浏览器才知道怎么解析你放回的数据
            response.setContentType("application/json;charset=UTF-8");
            //2.获取输出对象
            PrintWriter writer = response.getWriter();

            //3.把对象转成json字符串
            String s = JSONObject.toJSONString(result);

            //4.输出json字符串回去
            writer.write(s);

            return false;
        }

        //2.从redis中token作为key,拿到之前存进去登录对象UserInfo对象,如果拿不到,返回需要登录的code
        UserInfo userInfo = redisService.getKeyObjectValue(token, UserInfo.class);
        if (userInfo == null){
            //1.只能告诉前端2000的code(约定的登录失效的code)
            //除了分页,所有的都返回AjaxResult
            AjaxResult result = AjaxResult.createError(PetConstant.LOGIN_TIME_OUT, "登录失效");
            //1.1设置返回的类型,浏览器才知道怎么解析你放回的数据
            response.setContentType("application/json;charset=UTF-8");
            //2.获取输出对象
            PrintWriter writer = response.getWriter();

            //3.把对象转成json字符串
            String s = JSONObject.toJSONString(result);

            //4.输出json字符串回去
            writer.write(s);

            return false;
        }

        //3.重新存30分钟,刷新时间
        redisService.setStringKeyAndValue(token,userInfo,30);

        //4.放行
        return true;
    }
}
